﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTO;
using System.Data.SqlClient;
using System.Data;

namespace DAO
{
    public class CT_PhieuXuatKhoDAO
    {
        public List<CT_PhieuXuatKhoDTO> LayChiTietPhieuXuatKhoTheoMa(int mapxk)
        {
            List<CT_PhieuXuatKhoDTO> listCTPXK = new List<CT_PhieuXuatKhoDTO>();
            SqlConnection conn = null;
            SqlDataReader reader = null;
            try
            {
                String sql = "Select MaPhieuXK, ct.MaNVL, Ten, DonViTinh, DonGiaBan from CTPhieuXuatKho ct, NguyenVatLieu_SanPhamGiaiKhat sp Where MaPhieuXK = " + mapxk + " and ct.MaNVL = sp.MaNVL";

                conn = DataProvider.ConnectDB();
                SqlCommand cm = new SqlCommand(sql, conn);
                reader = cm.ExecuteReader();
                while (reader.Read())
                {
                    CT_PhieuXuatKhoDTO pnkDTO = new CT_PhieuXuatKhoDTO();
                    pnkDTO.MaPhieuXK = reader.GetInt32(0);
                    pnkDTO.MaNVL = reader.GetInt32(1);
                    pnkDTO.Ten = reader.GetString(2);
                    pnkDTO.DonViTinh = reader.GetString(3);
                    pnkDTO.Gia = Convert.ToDouble(reader.GetDecimal(4));

                    listCTPXK.Add(pnkDTO);
                }
            }
            catch (Exception ex)
            { String e = ex.ToString(); }
            finally
            { conn.Close(); }
            return listCTPXK;
        }

        public String ThemChiTietPhieuXuatKho(CT_PhieuXuatKhoDTO ctpxkDTO)
        {
            String mess = "";
            SqlConnection conn = null;
            try
            {
                conn = DataProvider.ConnectDB();
                String sql = "INSERT INTO CTPhieuXuatKho(MaPhieuXK,MaNVL,SoLuong)";
                sql += "VALUES(@MaPhieuXK,@MaNVL,@SoLuong)";
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                SqlParameter para;
                para = cmd.Parameters.Add("@MaPhieuXK", SqlDbType.Int);
                para.Value = ctpxkDTO.MaPhieuXK;
                para = cmd.Parameters.Add("@MaNVL", SqlDbType.Int);
                para.Value = ctpxkDTO.MaNVL;
                para = cmd.Parameters.Add("@SoLuong", SqlDbType.Int);
                para.Value = ctpxkDTO.SoLuong;


                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                mess = "Lỗi thêm chi tiết phiếu xuất kho";
                String e = ex.ToString();
            }
            finally
            {
                conn.Close();
            }
            return mess;
        }
    }
}
